package com.example.demo.controller;

import com.example.demo.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;

/**
 * @description:
 * @author: yyc
 * @time: 2021/11/24 15:40
 */
@Slf4j
@RestController
public class MyTestControlelr {

    @Autowired
    private EmailService emailService;

    @GetMapping("/email")
    public Callable<String> order(){
        log.info("主线程开启...");

        //副线程
        Callable<String> result = ()-> {
            log.info("副线程开启...");
            Thread.sleep(15000);
            log.info("副线程返回...");
            return "success";
        };
        log.info("主线程返回...");
        log.info("res:{}",result.toString());
        return result;
    }

    @GetMapping("/testAsync")
    public void testSend(){
//        emailService.sendEmail("yunshan_caigou2021@163.com","1291207970@qq.com","test","异步");
        emailService.sendEmail("1291207970@qq.com","异步");
        log.info("其他业务...");
    }

    /**
     * 多线程Thread
     * @return
     */
    @GetMapping("/testMulThread")
    public String testMulThread(){
        log.info("主线程start...");
        new Thread(
                ()->{
                    emailService.sendEmail("goatyyc@163.com","多线程thread","test");
                }
        ).start();
        log.info("主线程end...");
        return "success";
    }

    @GetMapping("/webAsyncTask")
    public WebAsyncTask<String> webAsyncTask(){
        log.info("外部线程:{}",Thread.currentThread().getName());
        WebAsyncTask<String> result = new WebAsyncTask<>(60 * 1000L, new Callable<String>() {

            @Override
            public String call() throws Exception {
                log.info("内部线程:{}", Thread.currentThread().getName());
                return "success";
            }
        });

        /**
         * 超时回调
         */
        result.onTimeout(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("timeout callback");
                return "timeout callback";
            }
        });

        /**
         * 完成回调
         */
        result.onCompletion(new Runnable() {
            @Override
            public void run() {
                emailService.sendEmail("goatyyc@163.com","webAsync","tt");
                log.info("finish callback");
            }
        });

        return result;
    }
}
